<template>
  <view class="materials-section">
    <text class="section-title">甲供材料</text>

    <view v-if="jgList.length === 0" class="empty-message">
      暂无甲供材料数据
    </view>

    <!-- 否则渲染一个简单的表格，后续可根据实际字段修改 -->
    <view v-else class="table-wrapper">
      <table class="data-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>材料名称</th>
            <th>规格型号</th>
            <th>数量</th>
            <th>单位</th>
            <!-- <th>单价</th> -->
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(item, idx) in jgList"
            :key="idx"
            @click="toggleRow(idx)"
            @dblclick="onRowDoubleClick(item)"
            :class="{ 
              'selected-row': jgSelectedIndices.has(idx),
              'modified-row': isRowModified(item)
            }"
          >
            <td style="width: 5%;">{{ idx + 1 }}</td>
            <td style="width: 20%;">{{ item.mat_name }}</td>
            <td style="width: 10%;">{{ item.mat_type }}</td>
            <td style="width: 10%;">{{ item.mat_count }}</td>
            <td style="width: 10%;">{{ item.mat_unit }}</td>
            <!-- <td style="width: 10%;">{{ item.mat_price }}</td> -->
          </tr>
        </tbody>
      </table>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from "vue";

const props = defineProps({
  jgList: {
    type: Array,
    default: () => [],
  },
  pendingChanges: {
    type: Array,
    default: () => []
  },
  modifiedRecords: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['row-double-click', 'project-changed', 'site-changed']);

const jgSelectedIndices = ref(new Set());
const lastProjectId = ref(null);
const lastSiteId = ref(null);

watch(
  () => props.jgList,
  () => {
    jgSelectedIndices.value.clear();
  }
);

// 组件挂载时初始化项目监听
onMounted(() => {
  initProjectWatch();
});

// 初始化项目和站点变化监听
function initProjectWatch() {
  // 获取初始项目ID和站点ID
  if (typeof window !== 'undefined') {
    if (window.currentProjectId) {
      lastProjectId.value = window.currentProjectId;
      console.log('JG材料-初始项目ID:', window.currentProjectId);
    }
    if (window.currentSiteId) {
      lastSiteId.value = window.currentSiteId;
      console.log('JG材料-初始站点ID:', window.currentSiteId);
    }
  }
  
  // 监听项目和站点变化
  const checkChanges = setInterval(() => {
    if (typeof window !== 'undefined') {
      // 检查项目变化
      const currentProjectId = window.currentProjectId;
      if (currentProjectId !== lastProjectId.value) {
        lastProjectId.value = currentProjectId;
        console.log('JG材料-项目已切换到:', currentProjectId);
        jgSelectedIndices.value.clear();
        emit('project-changed', currentProjectId);
      }
      
      // 检查站点变化
      const currentSiteId = window.currentSiteId;
      if (currentSiteId !== lastSiteId.value) {
        lastSiteId.value = currentSiteId;
        console.log('JG材料-站点已切换到:', currentSiteId);
        jgSelectedIndices.value.clear();
        emit('site-changed', currentSiteId);
      }
    }
  }, 500); // 每500ms检查一次
  
  // 组件卸载时清理定时器
  onUnmounted(() => {
    clearInterval(checkChanges);
  });
}

function toggleRow(idx) {
  console.log("JG材料-当前项目ID:", window.currentProjectId);
  console.log("JG材料-当前站点ID:", window.currentSiteId);
  if (jgSelectedIndices.value.has(idx)) {
    jgSelectedIndices.value.delete(idx);
  } else {
    jgSelectedIndices.value.add(idx);
  }
}

// 处理行双击事件
function onRowDoubleClick(item, rowIndex) {
  emit('row-double-click', item, 'jg', rowIndex);
}

// 检查行是否已被修改（暂存）
function isRowModified(item) {
  // 首先检查全局暂存记录
  if (typeof window !== 'undefined') {
    // 确保必要的全局变量存在
    if (!window.currentProjectId || !window.currentSiteId) {
      console.warn('项目ID或站点ID为空，无法检查暂存记录');
      return false;
    }
    
    // 初始化存储对象（如果不存在）
    if (!window.recordUpdateStorage) {
      window.recordUpdateStorage = {};
    }
    
    const recordKey = `${window.currentProjectId}_${window.currentSiteId}_${item.id}_jg`;
    console.log('=== JG材料暂存检查 ===');
    console.log('生成的Key:', recordKey);
    console.log('暂存记录存在:', !!window.recordUpdateStorage[recordKey]);
    
    if (window.recordUpdateStorage[recordKey]) {
      console.log('✅ JG材料找到暂存记录，应该显示绿色高亮');
      return true;
    }
  }
  
  // 检查已提交的修改记录
  if (props.modifiedRecords && props.modifiedRecords.length > 0) {
    const itemId = item.id || item.de_id || item.ID || item.De_id;
    if (itemId && window.currentProjectId && window.currentSiteId) {
      // 使用与 classic.vue 中相同的格式
      const recordKey = `${window.currentProjectId}_${window.currentSiteId}_${itemId}_jg`;
      console.log('=== JG材料已修改记录检查 ===');
      console.log('生成的recordKey:', recordKey);
      console.log('modifiedRecords列表:', props.modifiedRecords);
      console.log('是否匹配:', props.modifiedRecords.includes(recordKey));
      
      if (props.modifiedRecords.includes(recordKey)) {
        return true;
      }
    }
  }
  
  // 然后检查 pendingChanges
  if (props.pendingChanges && props.pendingChanges.length > 0) {
    const itemId = item.id || item.de_id || item.ID || item.De_id;
    const hasPendingChange = props.pendingChanges.some(change => 
      String(change.originalRecordId) === String(itemId) && 
      change.type === 'jg'
    );
    
    if (hasPendingChange) {
      console.log('✅ JG材料找到pendingChanges记录，应该显示绿色高亮');
      return true;
    }
  }
  
  return false;
}
</script>

<style scoped>
.materials-section {
  margin-bottom: 20px;
}
.section-title {
  font-size: 17px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #333;
  display: flex;
  align-items: center;
}
.section-title::before {
  content: "";
  width: 4px;
  height: 18px;
  background-color: #409eff;
  border-radius: 2px;
  margin-right: 8px;
}
.empty-message {
  padding: 24px 16px;
  color: #999;
  font-size: 14px;
  text-align: center;
  background-color: #fff;
  border-radius: 8px;
}
.table-wrapper {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
.data-table {
  width: 100%;
  border-collapse: collapse;
}
.data-table th,
.data-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  text-align: left;
  font-size: 14px;
  color: #333;
  word-break: break-word;
}
.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #606266;
}
.data-table tr:last-child td {
  border-bottom: none;
}
.data-table tr:nth-child(even) {
  background-color: #fafafa;
}
/* 选中行高亮 */
.selected-row {
  background-color: #1e3a8a !important;
  color: #fff;
}

.selected-row td {
  color: #fff;
}

/* 已修改行的绿色高亮 */
.modified-row {
  background-color: #f0f9ff !important;
  border: 2px solid #67c23a;
  animation: modifiedHighlight 1s ease-in-out;
}

.modified-row td {
  color: #67c23a;
  font-weight: 600;
}

@keyframes modifiedHighlight {
  0% {
    background-color: #fff;
    border-color: transparent;
  }
  50% {
    background-color: #e8f5e8;
    border-color: #67c23a;
  }
  100% {
    background-color: #f0f9ff;
    border-color: #67c23a;
  }
}

/* 当行既被选中又被修改时的样式优先级 */
.selected-row.modified-row {
  background-color: #67c23a !important;
  border-color: #67c23a;
}

.selected-row.modified-row td {
  color: #fff !important;
}
</style>